package com.common.sevice.impl;

import com.common.entity.SystemApplicationServiceEntity;
import com.common.model.SystemApplicationServiceModel;
import com.common.mysql.Where;
import com.common.service.impl.SimpleServiceImpl;
import com.common.service.impl.TreeSimpleServiceImpl;
import com.common.sevice.SystemApplicationModelService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Date: 2025/6/30 13:23
 */
@Service
public class SystemApplicationModelServiceImpl extends TreeSimpleServiceImpl<String, SystemApplicationServiceModel, SystemApplicationServiceEntity> implements SystemApplicationModelService {
    @Override
    public List<SystemApplicationServiceModel> list(Map<String, Object> params, String appId) {
        List<SystemApplicationServiceModel> applicationServiceModelList = search(Where.build()
                .field("app_id").equal(appId)
                .and()
                .field("del_flag").equal(0));
        return buildTree(applicationServiceModelList);
    }

    @Override
    public void deleteChildren(String id) {
        List<SystemApplicationServiceModel> applicationServiceModelList = searchAll();
        Map<String, List<SystemApplicationServiceModel>> parentIdMap = applicationServiceModelList.stream()
                .filter(systemApplicationServiceModel -> !ObjectUtils.isEmpty(systemApplicationServiceModel.getParentId()))
                .collect(Collectors.groupingBy(SystemApplicationServiceModel::getParentId));
        List<String> deleteIdList = new LinkedList<>();
        getDeleteIdList(parentIdMap, id, deleteIdList);
        deleteIdList.forEach(this::delete);
        delete(id);
    }

    private void getDeleteIdList(Map<String, List<SystemApplicationServiceModel>> parentIdMap, String id, List<String> deleteIdList) {
        if (parentIdMap.containsKey(id)) {
            List<SystemApplicationServiceModel> childrenList = parentIdMap.get(id);
            for (SystemApplicationServiceModel model : childrenList) {
                deleteIdList.add(model.getId());
                getDeleteIdList(parentIdMap, model.getId(), deleteIdList);
            }
        }
    }


}
